//
//  AppDelegate.m
//  Cunli
//
//  Created by lilubin on 15/6/1.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginningVC.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMessage.h"
#import "EaseMobHeaders.h"
#import "AppDelegate+EaseMob.h"
#import "MobClick.h"
#import "LoginVC_new.h"

//测试控制器
//#import "CompleteDataTableVC.h"

#define KNOTIFICATIONJUMP @"notificationjump"
#define KCLLOGINOUT @"loginout"
#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000

@interface AppDelegate ()
{
    
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
#pragma mark - 设置友盟推送
    
    //Cunli_iOSBeatV: 56936de3e0f55a2adb001c19  Cunli_iOS: 558bfc9667e58e648b000b25
    [UMessage startWithAppkey:@"558bfc9667e58e648b000b25" launchOptions:launchOptions];
    
    [MobClick startWithAppkey:@"558bfc9667e58e648b000b25" reportPolicy:BATCH channelId:nil];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif
    
    //for log
    [UMessage setLogEnabled:YES];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
#pragma mark - 环信初始化（含推送）
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
#pragma mark - 测试单独控制器
    /*
    CompleteDataTableVC *tempVC = [[CompleteDataTableVC alloc] init];
    [self.window setRootViewController:tempVC];
    */
#pragma mark - 正式的方法
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut) name:KCLLOGINOUT object:nil];
    LoginningVC *rootVC = [[LoginningVC alloc] init];
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        rootVC.launchOptions = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    }
    self.window.rootViewController = rootVC;
    
    [self.window makeKeyAndVisible];

    //注册友盟社会化组件
    [UMSocialData setAppKey:@"558bfc9667e58e648b000b25"];
    [UMSocialWechatHandler setWXAppId:@"wx46e3a9ebb398cb18" appSecret:@"d3fc8a9c48e99e0c4837ba3525830ab4" url:@"http://www.umeng.com/social"];
    [UMSocialQQHandler setQQWithAppId:@"1104693573" appKey:@"apX8vFPjxNLu8g2b" url:@"http://www.umeng.com/social"];
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
    
    return YES;
}

- (void)loginOut
{
    LoginVC_new *loginVC = [[LoginVC_new alloc] init];
    loginVC.netCheck = @"";
    [self.window setRootViewController:loginVC];
}

/*
- (void)postNotificationZhanyaa:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATIONJUMP object:userInfo];
}
*/
- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    
    NSMutableArray *ret = nil;
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    
    NSArray* sorte = [conversations sortedArrayUsingComparator:
                      ^(EMConversation *obj1, EMConversation* obj2){
                          EMMessage *message1 = [obj1 latestMessage];
                          EMMessage *message2 = [obj2 latestMessage];
                          if(message1.timestamp > message2.timestamp) {
                              return(NSComparisonResult)NSOrderedAscending;
                          }else {
                              return(NSComparisonResult)NSOrderedDescending;
                          }
                      }];
    
    ret = [[NSMutableArray alloc] initWithArray:sorte];
    
    NSInteger unReadMessageCount=0;
    for (int i=0; i<ret.count; i++) {
        EMConversation *conversation=[ret objectAtIndex:i];
        unReadMessageCount=unReadMessageCount+conversation.unreadMessagesCount;
    }
    
    application.applicationIconBadgeNumber = unReadMessageCount;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}

#pragma mark - 友盟推送设置1

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"Register deviceToken");
    //    [UMessage registerDeviceToken:deviceToken];
    /*
     [UMessage addTag:[Config getOwnAreaids] response:^(id responseObject, NSInteger remain, NSError *error) {
     NSLog(@"添加APSN失败:%@", error.userInfo);
     }];
     */
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //如果注册不成功，打印错误信息，可以在网上找到对应的解决方案
    //如果注册成功，可以删掉这个方法
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"---receive message---:%@", userInfo);
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateActive) {
        return;
    }
    if (application.applicationState == UIApplicationStateInactive) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATIONJUMP object:userInfo];
    }
}

extern "C"{
    size_t fwrite$UNIX2003(const void *a, size_t b, size_t c, FILE *d )
    {
        return fwrite(a, b, c, d);
    }
    
    char* strerror$UNIX2003( int errnum )
    {
        return strerror(errnum);
    }
}

@end
